<template>
  <div class="modern-dashboard" v-loading="loading">
    <!-- 统计卡片 - 可点击跳转 -->
    <div class="stats-grid">
      <component
        :is="stat.link ? 'router-link' : 'a'"
        v-for="(stat, index) in stats"
        :key="stat.id || index"
        :to="stat.link || undefined"
        :href="stat.href || undefined"
        :target="stat.target || undefined"
        class="stat-card glass-card hover-lift clickable"
        :style="{ animationDelay: `${index * 100}ms` }"
      >
        <div class="stat-icon" :style="{ background: stat.gradient }">
          <component :is="stat.iconComponent" class="stat-icon__glyph" />
        </div>
        <div class="stat-content">
          <div class="stat-label">{{ stat.label }}</div>
          <div class="stat-value">
            {{ stat.value }}
            <span
              v-if="typeof stat.badgeCount === 'number'"
              class="pending-badge"
              :class="{
                pulse: stat.badgePulse && stat.badgeCount > 0,
                empty: stat.badgeCount === 0
              }"
              :title="stat.badgeCount > 0 ? `有 ${stat.badgeCount} 个订单待处理` : '暂无待处理订单'"
              :style="{
                backgroundColor: stat.badgeCount > 0
                  ? (stat.badgeColor || '#f56c6c')
                  : '#dcdfe6',
                color: stat.badgeCount > 0 ? '#ffffff' : '#909399'
              }"
            >
              {{ stat.badgeCount }}
            </span>
          </div>
          <div class="stat-description">{{ stat.description }}</div>
        </div>
      </component>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 产品分类统计 -->
      <div class="chart-card glass-card">
        <div class="card-header">
          <h3>产品分类</h3>
          <router-link to="/products-integrated" class="view-all-link">查看全部</router-link>
        </div>
        <div class="category-list">
          <div v-for="(category, index) in categories" :key="index" class="category-item">
            <div class="category-info">
              <div class="category-icon" :style="{ background: category.gradient }">
                <component :is="category.iconComponent" class="category-icon__glyph" />
              </div>
              <div>
                <div class="category-name">{{ category.name }}</div>
                <div class="category-subtitle">{{ category.subtitle }}</div>
              </div>
            </div>
            <div class="category-stats">
              <span class="category-count">{{ category.count }}</span>
              <div class="category-bar">
                <div class="category-bar-fill" :style="{ width: category.percentage + '%', background: category.gradient }"></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 最近创建的产品 -->
      <div class="chart-card glass-card">
        <div class="card-header">
          <div>
            <h3>最近创建</h3>
            <p class="card-subtitle">最新添加的 5 个产品</p>
          </div>
          <router-link to="/products-integrated/create" class="view-all-link">创建产品</router-link>
        </div>
        <div class="recent-products">
          <div 
            v-for="product in recentProducts.slice(0, 5)" 
            :key="product.id" 
            class="product-item"
            @click="$router.push(`/products-integrated/${product.id}/edit`)"
          >
            <ImagePreview
              v-if="product.cover_image_url"
              :src="product.cover_image_url"
              width="48px"
              height="48px"
              fit="cover"
            />
            <div v-else class="product-placeholder">
              <el-icon><Picture /></el-icon>
            </div>
            <div class="product-info">
              <div class="product-name">{{ getProductName(product) }}</div>
              <div class="product-meta">
                <template v-if="product.categories_data && product.categories_data.length > 0">
                  <el-tag 
                    v-for="cat in product.categories_data" 
                    :key="cat.id"
                    :type="cat.slug === 'dog' ? 'success' : (cat.slug === 'cat' ? 'warning' : 'info')"
                    size="small"
                    style="margin-right: 5px;"
                  >
                    {{ cat.name }}
                  </el-tag>
                </template>
                <span class="product-variants">{{ product.variants_data?.length || 0 }} 个变体</span>
              </div>
            </div>
            <el-tag :type="product.is_active ? 'success' : 'info'" size="small">
              {{ product.is_active ? '激活' : '未激活' }}
            </el-tag>
          </div>
          <div v-if="recentProducts.length === 0" class="empty-state">
            <el-icon size="48" color="#ccc"><Box /></el-icon>
            <p>暂无产品</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { Component } from 'vue'
import { ElMessage } from 'element-plus'
import { Goods, List, Message, Picture, Collection, CollectionTag, Box } from '@element-plus/icons-vue'
import { getDashboardStats, getRecentProducts, getCategoryStats } from '@/api/dashboard'
import ImagePreview from '@/components/ImagePreview.vue'

const loading = ref(false)

interface StatItem {
  id: string
  label: string
  value: string
  description: string
  gradient: string
  link?: string
  badgeCount?: number
  badgeColor?: string
  badgePulse?: boolean
  iconComponent: Component
}

interface CategoryItem {
  name: string
  subtitle: string
  count: number
  percentage: number
  gradient: string
  iconComponent: Component
}

const stats = ref<StatItem[]>([
  {
    id: 'products',
    label: '总产品数',
    value: '0',
    description: '点击查看所有产品',
    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    link: '/products-integrated',
    iconComponent: Goods
  },
  {
    id: 'orders',
    label: '订单管理',
    value: '待处理订单',
    description: '点击查看并处理订单',
    gradient: 'linear-gradient(135deg, #ff9a9e 0%, #f6416c 100%)',
    badgeCount: 0,
    badgeColor: '#f56c6c',
    badgePulse: false,
    link: '/orders',
    iconComponent: List
  },
  {
    id: 'messages',
    label: '客户留言',
    value: '未读留言',
    description: '查看并回复客户消息',
    gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    badgeCount: 0,
    badgeColor: '#f56c6c',
    badgePulse: false,
    link: '/contact-messages',
    iconComponent: Message
  },
  {
    id: 'carousels',
    label: '轮播图数量',
    value: '0',
    description: '首页轮播图管理',
    gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    link: '/carousels',
    iconComponent: Picture
  }
])

const categories = ref<CategoryItem[]>([
  {
    name: '狗狗用品',
    subtitle: 'Dog Products',
    count: 0,
    percentage: 0,
    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    iconComponent: Collection
  },
  {
    name: '猫咪用品',
    subtitle: 'Cat Products',
    count: 0,
    percentage: 0,
    gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    iconComponent: CollectionTag
  }
])

const recentProducts = ref<any[]>([])

// 获取产品名称（优先中文）
const getProductName = (product: any) => {
  const zhTranslation = product.translations_data?.zh || product.translations_data?.['zh-CN']
  if (zhTranslation?.name) {
    return zhTranslation.name
  }
  const enTranslation = product.translations_data?.en || product.translations_data?.['en-US']
  if (enTranslation?.name) {
    return enTranslation.name
  }
  return '未命名产品'
}

const loadDashboardData = async () => {
  loading.value = true
  try {
    // 加载统计数据
    const [dashboardStats, categoryStatsData, recentProductsData] = await Promise.all([
      getDashboardStats(),
      getCategoryStats(),
      getRecentProducts(5)
    ])

    const productStat = stats.value.find(stat => stat.id === 'products')
    if (productStat) {
      productStat.value = dashboardStats.totalProducts.toString()
      productStat.description = '点击查看所有产品'
    }

    const orderStat = stats.value.find(stat => stat.id === 'orders')
    if (orderStat) {
      const pending = dashboardStats.pendingOrders || 0
      orderStat.badgeCount = pending
      orderStat.badgePulse = pending > 0
      orderStat.value = pending > 0 ? '待处理订单' : '暂无待处理'
      orderStat.description = pending > 0 ? '请尽快处理用户订单' : '所有订单均已处理'
      orderStat.badgeColor = pending > 0 ? '#f56c6c' : '#dcdfe6'
    }

    const messageStat = stats.value.find(stat => stat.id === 'messages')
    if (messageStat) {
      const unread = dashboardStats.unreadMessages || 0
      messageStat.badgeCount = unread
      messageStat.badgePulse = unread > 0
      messageStat.value = unread > 0 ? '未读留言' : '暂无未读'
      messageStat.description = unread > 0 ? '请尽快回复客户留言' : '所有留言均已处理'
      messageStat.badgeColor = unread > 0 ? '#f56c6c' : '#dcdfe6'
    }

    const carouselStat = stats.value.find(stat => stat.id === 'carousels')
    if (carouselStat) {
      carouselStat.value = dashboardStats.totalCarousels.toString()
      carouselStat.description = '首页轮播图管理'
    }

    // 更新分类统计
    const dogStats = categoryStatsData.find(c => c.category === 'dog')
    const catStats = categoryStatsData.find(c => c.category === 'cat')
    
    const dogCount = dogStats?.count || 0
    const catCount = catStats?.count || 0
    const total = dogCount + catCount

    categories.value[0].count = dogCount
    categories.value[0].percentage = total > 0 ? Math.round((dogCount / total) * 100) : 0
    
    categories.value[1].count = catCount
    categories.value[1].percentage = total > 0 ? Math.round((catCount / total) * 100) : 0

    // 更新最近产品
    recentProducts.value = recentProductsData

  } catch (error) {
    console.error('Failed to load dashboard data:', error)
    ElMessage.error('加载仪表盘数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.modern-dashboard {
  max-width: var(--container-max-width);
  margin: 0 auto;
  min-height: calc(100vh - 120px);
}

/* ========== 统计卡片 ========== */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: var(--spacing-2xl);
  margin-bottom: var(--spacing-4xl);
}

.stat-card {
  padding: var(--spacing-2xl);
  display: flex;
  gap: var(--spacing-lg);
  animation: fadeIn 0.5s ease-out backwards;
  cursor: default;
  text-decoration: none;
  color: inherit;
  display: flex;
}

.stat-card.clickable {
  cursor: pointer;
  transition: all var(--transition-base);
}

.stat-card.clickable:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-2xl);
}

.stat-card.clickable:active {
  transform: translateY(-2px);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
  box-shadow: var(--shadow-md);
}

.stat-icon svg,
.stat-icon__glyph {
  width: 28px;
  height: 28px;
}

.stat-content {
  flex: 1;
  min-width: 0;
}

.stat-label {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  margin-bottom: var(--spacing-xs);
  font-weight: var(--font-weight-medium);
}

.stat-value {
  font-size: var(--font-size-4xl);
  font-weight: var(--font-weight-bold);
  color: var(--color-text-primary);
  margin-bottom: var(--spacing-xs);
  line-height: 1.2;
}

.pending-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 40px;
  padding: 0 var(--spacing-sm);
  margin-left: var(--spacing-md);
  border-radius: 999px;
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-bold);
  box-shadow: 0 6px 16px rgba(245, 108, 108, 0.35);
  transition: transform var(--transition-base);
}

.pending-badge.empty {
  box-shadow: none;
}

.pending-badge.pulse {
  animation: pendingPulse 1.4s ease-in-out infinite;
}

@keyframes pendingPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.45);
  }
  70% {
    transform: scale(1.06);
    box-shadow: 0 0 0 12px rgba(245, 108, 108, 0);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

.stat-description {
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
}

/* ========== 主要内容区 ========== */
.main-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: var(--spacing-2xl);
  margin-bottom: var(--spacing-4xl);
}

.chart-card {
  padding: var(--spacing-2xl);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--spacing-2xl);
}

.card-header h3 {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
  margin: 0 0 4px 0;
}

.card-subtitle {
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
  margin: 0;
  font-weight: var(--font-weight-regular);
}

.view-all-link {
  font-size: var(--font-size-sm);
  color: var(--color-accent);
  text-decoration: none;
  font-weight: var(--font-weight-medium);
  transition: all var(--transition-base);
}

.view-all-link:hover {
  color: var(--color-accent-dark);
  transform: translateX(4px);
}

/* ========== 分类列表 ========== */
.category-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-2xl);
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--spacing-lg);
  padding: var(--spacing-lg);
  border-radius: var(--radius-lg);
  transition: all var(--transition-base);
}

.category-item:hover {
  background: var(--color-bg-secondary);
}

.category-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.category-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.category-icon svg,
.category-icon__glyph {
  width: 24px;
  height: 24px;
}

.category-name {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
  margin-bottom: 4px;
}

.category-subtitle {
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
}

.category-stats {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  flex: 1;
  max-width: 200px;
}

.category-count {
  font-size: var(--font-size-2xl);
  font-weight: var(--font-weight-bold);
  color: var(--color-text-primary);
  min-width: 48px;
  text-align: right;
}

.category-bar {
  flex: 1;
  height: 8px;
  background: var(--color-bg-tertiary);
  border-radius: var(--radius-full);
  overflow: hidden;
}

.category-bar-fill {
  height: 100%;
  border-radius: var(--radius-full);
  transition: width var(--transition-slow);
}

/* ========== 最近产品 ========== */
.recent-products {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.product-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-lg);
  border-radius: var(--radius-lg);
  transition: all var(--transition-base);
  cursor: pointer;
}

.product-item:hover {
  background: var(--color-bg-secondary);
  transform: translateX(4px);
}

.product-placeholder {
  width: 48px;
  height: 48px;
  background: var(--color-bg-tertiary);
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--color-text-tertiary);
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin-bottom: var(--spacing-xs);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-meta {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
}

.product-variants {
  font-size: var(--font-size-xs);
}

.empty-state {
  text-align: center;
  padding: var(--spacing-5xl) 0;
  color: var(--color-text-tertiary);
}

.empty-state p {
  margin-top: var(--spacing-md);
  font-size: var(--font-size-base);
}
</style>
